/**
 * 举报API库
 * @author HalRui
 * @version 1.0.0
 * @description 提供举报相关的业务逻辑函数，包括举报创建、查询、状态管理、处理流程、统计分析等功能
 * @date 2025年9月27日
 */

const Reports = require('../models/reports-model');
const UserInfos = require('../models/userinfos-model');
const Videos = require('../models/videos-model');

/**
 * 创建举报
 * @param {Object} reportData - 举报数据
 * @returns {Object} 操作结果
 */
async function createReport(reportData) {
    try {
        // 验证举报者是否存在
        const reporter = await UserInfos.findOne({
            userId: reportData.reporterId,
            isDeleted: false
        });
        
        if (!reporter) {
            return {
                success: false,
                message: '举报者不存在'
            };
        }
        
        // 验证被举报对象是否存在
        let targetExists = false;
        let targetUserId = null;
        
        switch (reportData.targetType) {
            case 'video':
                const video = await Videos.findOne({
                    videoId: reportData.targetId,
                    isDeleted: false
                });
                if (video) {
                    targetExists = true;
                    targetUserId = video.userId;
                }
                break;
                
            case 'user':
                const user = await UserInfos.findOne({
                    userId: reportData.targetId,
                    isDeleted: false
                });
                if (user) {
                    targetExists = true;
                    targetUserId = user.userId;
                }
                break;
                
            case 'comment':
            case 'message':
                // 这里可以根据实际的评论和消息模型进行验证
                targetExists = true;
                break;
        }
        
        if (!targetExists) {
            return {
                success: false,
                message: '被举报对象不存在'
            };
        }
        
        // 添加目标用户ID
        if (targetUserId) {
            reportData.targetUserId = targetUserId;
        }
        
        // 创建举报
        const result = await Reports.createReport(reportData);
        
        return result;
    } catch (error) {
        console.error('创建举报API错误:', error);
        return {
            success: false,
            message: '创建举报失败'
        };
    }
}

/**
 * 获取举报列表
 * @param {Object} options - 查询选项
 * @returns {Object} 操作结果
 */
async function getReportList(options = {}) {
    try {
        const result = await Reports.getReportList(options);
        
        if (result.success && result.data.reports.length > 0) {
            // 获取相关用户信息
            const reporterIds = [...new Set(result.data.reports.map(r => r.reporterId))];
            const handlerIds = [...new Set(result.data.reports.map(r => r.handlerId).filter(Boolean))];
            const targetUserIds = [...new Set(result.data.reports.map(r => r.targetUserId).filter(Boolean))];
            
            const allUserIds = [...new Set([...reporterIds, ...handlerIds, ...targetUserIds])];
            
            const users = await UserInfos.find({
                userId: { $in: allUserIds },
                isDeleted: false
            }).select('userId username nickname avatar').lean();
            
            const userMap = {};
            users.forEach(user => {
                userMap[user.userId] = {
                    userId: user.userId,
                    username: user.username,
                    nickname: user.nickname,
                    avatar: user.avatar
                };
            });
            
            // 添加用户信息到举报数据
            result.data.reports = result.data.reports.map(report => ({
                ...report,
                reporterInfo: userMap[report.reporterId] || null,
                handlerInfo: userMap[report.handlerId] || null,
                targetUserInfo: userMap[report.targetUserId] || null
            }));
        }
        
        return result;
    } catch (error) {
        console.error('获取举报列表API错误:', error);
        return {
            success: false,
            message: '获取举报列表失败'
        };
    }
}

/**
 * 获取举报详情
 * @param {Number} reportId - 举报ID
 * @returns {Object} 操作结果
 */
async function getReportDetail(reportId) {
    try {
        const result = await Reports.getReportDetail(reportId);
        
        if (result.success && result.data) {
            // 获取相关用户信息
            const userIds = [result.data.reporterId];
            if (result.data.handlerId) userIds.push(result.data.handlerId);
            if (result.data.targetUserId) userIds.push(result.data.targetUserId);
            
            // 获取管理员备注中的用户ID
            if (result.data.adminNotes && result.data.adminNotes.length > 0) {
                result.data.adminNotes.forEach(note => {
                    if (note.adminId) userIds.push(note.adminId);
                });
            }
            
            const uniqueUserIds = [...new Set(userIds)];
            
            const users = await UserInfos.find({
                userId: { $in: uniqueUserIds },
                isDeleted: false
            }).select('userId username nickname avatar').lean();
            
            const userMap = {};
            users.forEach(user => {
                userMap[user.userId] = {
                    userId: user.userId,
                    username: user.username,
                    nickname: user.nickname,
                    avatar: user.avatar
                };
            });
            
            // 添加用户信息
            result.data.reporterInfo = userMap[result.data.reporterId] || null;
            result.data.handlerInfo = userMap[result.data.handlerId] || null;
            result.data.targetUserInfo = userMap[result.data.targetUserId] || null;
            
            // 为管理员备注添加用户信息
            if (result.data.adminNotes && result.data.adminNotes.length > 0) {
                result.data.adminNotes = result.data.adminNotes.map(note => ({
                    ...note,
                    adminInfo: userMap[note.adminId] || null
                }));
            }
            
            // 获取被举报对象的详细信息
            if (result.data.targetType === 'video') {
                const video = await Videos.findOne({
                    videoId: result.data.targetId,
                    isDeleted: false
                }).select('videoId title description thumbnail duration').lean();
                
                if (video) {
                    result.data.targetInfo = video;
                }
            }
        }
        
        return result;
    } catch (error) {
        console.error('获取举报详情API错误:', error);
        return {
            success: false,
            message: '获取举报详情失败'
        };
    }
}

/**
 * 更新举报状态
 * @param {Number} reportId - 举报ID
 * @param {String} status - 新状态
 * @param {Number} handlerId - 处理人员ID
 * @returns {Object} 操作结果
 */
async function updateReportStatus(reportId, status, handlerId) {
    try {
        // 验证处理人员是否存在
        if (handlerId) {
            const handler = await UserInfos.findOne({
                userId: handlerId,
                isDeleted: false
            });
            
            if (!handler) {
                return {
                    success: false,
                    message: '处理人员不存在'
                };
            }
        }
        
        const result = await Reports.updateReportStatus(reportId, status, handlerId);
        
        return result;
    } catch (error) {
        console.error('更新举报状态API错误:', error);
        return {
            success: false,
            message: '更新举报状态失败'
        };
    }
}

/**
 * 处理举报
 * @param {Number} reportId - 举报ID
 * @param {Object} resolutionData - 处理结果数据
 * @param {Number} handlerId - 处理人员ID
 * @returns {Object} 操作结果
 */
async function resolveReport(reportId, resolutionData, handlerId) {
    try {
        // 验证处理人员是否存在
        const handler = await UserInfos.findOne({
            userId: handlerId,
            isDeleted: false
        });
        
        if (!handler) {
            return {
                success: false,
                message: '处理人员不存在'
            };
        }
        
        const result = await Reports.resolveReport(reportId, resolutionData, handlerId);
        
        return result;
    } catch (error) {
        console.error('处理举报API错误:', error);
        return {
            success: false,
            message: '处理举报失败'
        };
    }
}

/**
 * 添加管理员备注
 * @param {Number} reportId - 举报ID
 * @param {Number} adminId - 管理员ID
 * @param {String} note - 备注内容
 * @returns {Object} 操作结果
 */
async function addAdminNote(reportId, adminId, note) {
    try {
        // 验证管理员是否存在
        const admin = await UserInfos.findOne({
            userId: adminId,
            isDeleted: false
        });
        
        if (!admin) {
            return {
                success: false,
                message: '管理员不存在'
            };
        }
        
        const result = await Reports.addAdminNote(reportId, adminId, note);
        
        return result;
    } catch (error) {
        console.error('添加管理员备注API错误:', error);
        return {
            success: false,
            message: '添加管理员备注失败'
        };
    }
}

/**
 * 删除举报
 * @param {Number} reportId - 举报ID
 * @returns {Object} 操作结果
 */
async function deleteReport(reportId) {
    try {
        const result = await Reports.deleteReport(reportId);
        
        return result;
    } catch (error) {
        console.error('删除举报API错误:', error);
        return {
            success: false,
            message: '删除举报失败'
        };
    }
}

/**
 * 获取举报统计信息
 * @param {Object} options - 统计选项
 * @returns {Object} 操作结果
 */
async function getReportStats(options = {}) {
    try {
        const result = await Reports.getReportStats(options);
        
        return result;
    } catch (error) {
        console.error('获取举报统计API错误:', error);
        return {
            success: false,
            message: '获取举报统计失败'
        };
    }
}

/**
 * 获取用户举报历史
 * @param {Number} reporterId - 举报者ID
 * @param {Object} options - 查询选项
 * @returns {Object} 操作结果
 */
async function getUserReportHistory(reporterId, options = {}) {
    try {
        // 验证用户是否存在
        const user = await UserInfos.findOne({
            userId: reporterId,
            isDeleted: false
        });
        
        if (!user) {
            return {
                success: false,
                message: '用户不存在'
            };
        }
        
        const result = await Reports.getUserReportHistory(reporterId, options);
        
        return result;
    } catch (error) {
        console.error('获取用户举报历史API错误:', error);
        return {
            success: false,
            message: '获取用户举报历史失败'
        };
    }
}

/**
 * 批量更新举报状态
 * @param {Array} reportIds - 举报ID列表
 * @param {String} status - 新状态
 * @param {Number} handlerId - 处理人员ID
 * @returns {Object} 操作结果
 */
async function batchUpdateReportStatus(reportIds, status, handlerId) {
    try {
        // 验证处理人员是否存在
        if (handlerId) {
            const handler = await UserInfos.findOne({
                userId: handlerId,
                isDeleted: false
            });
            
            if (!handler) {
                return {
                    success: false,
                    message: '处理人员不存在'
                };
            }
        }
        
        const updateData = { status };
        if (handlerId) updateData.handlerId = handlerId;
        
        const result = await Reports.updateMany(
            {
                reportId: { $in: reportIds },
                isDeleted: false
            },
            updateData
        );
        
        return {
            success: true,
            message: `成功更新 ${result.modifiedCount} 个举报的状态`,
            data: {
                matched: result.matchedCount,
                modified: result.modifiedCount
            }
        };
    } catch (error) {
        console.error('批量更新举报状态API错误:', error);
        return {
            success: false,
            message: '批量更新举报状态失败'
        };
    }
}

/**
 * 分配处理人员
 * @param {Number} reportId - 举报ID
 * @param {Number} handlerId - 处理人员ID
 * @returns {Object} 操作结果
 */
async function assignHandler(reportId, handlerId) {
    try {
        // 验证处理人员是否存在
        const handler = await UserInfos.findOne({
            userId: handlerId,
            isDeleted: false
        });
        
        if (!handler) {
            return {
                success: false,
                message: '处理人员不存在'
            };
        }
        
        // 获取举报
        const report = await Reports.findOne({
            reportId,
            isDeleted: false
        });
        
        if (!report) {
            return {
                success: false,
                message: '举报不存在'
            };
        }
        
        // 分配处理人员
        await report.assignHandler(handlerId);
        
        return {
            success: true,
            message: '处理人员分配成功',
            data: report.getSafeJSON()
        };
    } catch (error) {
        console.error('分配处理人员API错误:', error);
        return {
            success: false,
            message: '分配处理人员失败'
        };
    }
}

/**
 * 更新举报优先级
 * @param {Number} reportId - 举报ID
 * @param {String} priority - 新优先级
 * @returns {Object} 操作结果
 */
async function updateReportPriority(reportId, priority) {
    try {
        // 获取举报
        const report = await Reports.findOne({
            reportId,
            isDeleted: false
        });
        
        if (!report) {
            return {
                success: false,
                message: '举报不存在'
            };
        }
        
        // 更新优先级
        await report.updatePriority(priority);
        
        return {
            success: true,
            message: '优先级更新成功',
            data: report.getSafeJSON()
        };
    } catch (error) {
        console.error('更新举报优先级API错误:', error);
        return {
            success: false,
            message: '更新举报优先级失败'
        };
    }
}

/**
 * 获取举报类型列表
 * @returns {Object} 操作结果
 */
async function getReportTypes() {
    try {
        const reportTypes = [
            { value: 'spam', label: '垃圾信息', description: '发送垃圾邮件、广告或重复内容' },
            { value: 'harassment', label: '骚扰', description: '骚扰、威胁或恶意行为' },
            { value: 'hate_speech', label: '仇恨言论', description: '基于种族、性别、宗教等的仇恨言论' },
            { value: 'violence', label: '暴力内容', description: '包含暴力、血腥或危险内容' },
            { value: 'adult_content', label: '成人内容', description: '包含成人或不当内容' },
            { value: 'copyright', label: '版权侵犯', description: '未经授权使用受版权保护的内容' },
            { value: 'misinformation', label: '虚假信息', description: '传播虚假或误导性信息' },
            { value: 'privacy', label: '隐私侵犯', description: '侵犯个人隐私或泄露个人信息' },
            { value: 'fraud', label: '欺诈', description: '欺诈、诈骗或虚假声明' },
            { value: 'other', label: '其他', description: '其他违规行为' }
        ];
        
        return {
            success: true,
            data: reportTypes
        };
    } catch (error) {
        console.error('获取举报类型列表API错误:', error);
        return {
            success: false,
            message: '获取举报类型列表失败'
        };
    }
}

module.exports = {
    createReport,
    getReportList,
    getReportDetail,
    updateReportStatus,
    resolveReport,
    addAdminNote,
    deleteReport,
    getReportStats,
    getUserReportHistory,
    batchUpdateReportStatus,
    assignHandler,
    updateReportPriority,
    getReportTypes
};